package com.example.thread.demo.alternate.print2;

public class Solution {

    private static final Object lock = new Object();// 对象锁

    private volatile int i = 1;// 要输出的数字

    private volatile boolean flag = false;// 记录A是否被打印过

    class A implements Runnable {
        @Override
        public void run() {
            for (int j = 0; j < 50; j++) {
                synchronized (lock) {
                    while (flag) { // 如果A已经打印过就进行阻塞
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("A: " + i);//A没有打印过则输出A的值
                    i++;//输出的值增加1
                    flag = true;//表示A已经打印过
                    lock.notifyAll();//唤醒其它线程执行
                }
            }
        }
    }

    class B implements Runnable {
        @Override
        public void run() {
            for (int j = 0; j < 50; j++) {
                synchronized (lock) {
                    while (!flag) {//如果A没有打印过则阻塞
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("B: " + i);//输出B的值
                    i++;//计数加一
                    flag = false;//B打印完了说明新的一轮开始了，将标识为计为A没有打印过
                    lock.notifyAll();//唤醒阻塞线程
                }
            }
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        Thread t1 = new Thread(solution.new A());
        Thread t2 = new Thread(solution.new B());
        t1.start();
        t2.start();
    }
}
